package com.neihe.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neihe.common.base.ApiException;
import com.neihe.entity.ShareFile;
import com.neihe.entity.dto.share.SaveShareFilesContextDTO;
import com.neihe.mapper.ShareFileMapper;
import com.neihe.service.IShareFileService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ShareFileServiceImpl extends ServiceImpl<ShareFileMapper, ShareFile> implements IShareFileService {

    /**
     * 保存分享的文件的对应关系
     */
    @Override
    @Transactional(rollbackFor = ApiException.class)
    public void saveShareFiles(SaveShareFilesContextDTO context) {
        Long shareId = context.getShareId();
        List<Long> shareFileIds = context.getShareFileIds();
        Long userId = context.getUserId();

        List<ShareFile> records = CollUtil.newArrayList();

        for (Long shareFileId : shareFileIds) {
            ShareFile record = new ShareFile();
            record.setShareId(shareId);
            record.setFileId(shareFileId);
            record.setUserId(userId);
            record.setCreateTime(new Date());
            records.add(record);
        }

        if (!saveBatch(records)) {
            throw new ApiException("内部错误，保存文件分享关联关系失败");
        }
    }

}

